<template>
  <div class="personal-center-page">
    <div class="nav-header" @click="goHome">← 返回首页</div>
    <div class="personal-center-container">
      <div class="personal-info-card">
        <h2>👤 个人信息</h2>
        <div v-if="user">
          <p><strong>用户ID：</strong>{{ user.userId }}</p>
          <p><strong>用户名：</strong>{{ user.username }}</p>
          <p><strong>真实姓名：</strong>{{ user.realName }}</p>
          <p><strong>身份证号：</strong>{{ maskedIdCardNumber }}</p>
          <p><strong>手机号：</strong>{{ maskedPhoneNumber }}</p>
          <p><strong>用户类型：</strong>{{ userTypeLabel }}</p>
          <p><strong>账户状态：</strong>{{ user.active ? '正常' : '已禁用' }}</p>
          <p><strong>账户余额：</strong>￥{{ formatBalance(user.balance) }}</p>
          <p><strong>注册时间：</strong>{{ formattedRegistrationTime }}</p>
          <p><strong>最后登录：</strong>{{ formattedLastLoginTime }}</p>
        </div>
        <div v-else>
          <p>加载中...</p>
        </div>
      </div>

      <div class="personal-edit-card">
        <h2>✏️ 修改信息</h2>

        <h3>修改用户名</h3>
        <input v-model="newUsername" placeholder="请输入新用户名" />
        <button @click="updateUsername">保存用户名</button>

        <h3>修改密码</h3>
        <input type="password" v-model="oldPassword" placeholder="请输入旧密码" />
        <input type="password" v-model="newPassword" placeholder="请输入新密码" />
        <button @click="updatePassword">保存密码</button>

        <h3>账户充值</h3>
        <input
          v-model="rechargeAmount"
          type="number"
          placeholder="请输入充值金额"
          min="0"
          step="0.01"
        />
        <button @click="handleRecharge">充值</button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import api from '@/utils/api'
import type { UserInfoDTO } from '@/types/UserInfoDTO.ts'
import { useRouter } from 'vue-router'

const router = useRouter()
const route = useRoute()
const username = ref(route.query.username as string)
const user = ref<UserInfoDTO | null>(null)
const newUsername = ref('')
const oldPassword = ref('')
const newPassword = ref('')
const rechargeAmount = ref('')
// 根据用户类型代码显示标签
const userTypeLabel = computed(() => {
  switch (user.value?.userType) {
    case 0:
      return '普通用户'
    case 1:
      return '学生'
    case 2:
      return '特殊群体'
    case 3:
      return '管理员'
    default:
      return '未知'
  }
})

// 格式化注册时间
const formattedRegistrationTime = computed(() => {
  return user.value?.registrationTime?.replace('T', ' ').slice(0, 16) ?? ''
})

// 格式化最后登录时间
const formattedLastLoginTime = computed(() => {
  return user.value?.lastLoginTime?.replace('T', ' ').slice(0, 16) ?? '从未登录'
})

// 格式化余额
const formatBalance = (balance: number) => {
  return balance.toFixed(2)
}

//身份证号码隐藏展示
const maskedIdCardNumber = computed(() => {
  if (!user.value?.idCardNumber) return ''
  const id = user.value.idCardNumber
  return id.slice(0, 3) + '*'.repeat(id.length - 3)
})

//手机号码隐藏展示
const maskedPhoneNumber = computed(() => {
  if (!user.value?.phoneNumber) return ''
  const phone = user.value.phoneNumber
  return phone.slice(0, 3) + '****' + phone.slice(phone.length - 4)
})

// 请求用户信息
async function fetchUserInfo() {
  try {
    const res = await api.get(`/api/users?username=${encodeURIComponent(username.value)}`)
    user.value = res.data
  } catch (error) {
    console.error('获取用户信息失败', error)
  }
}
// 修改用户名
async function updateUsername() {
  if (!newUsername.value) return alert('新用户名不能为空')
  if (newUsername.value == user.value?.username) {
    return alert('新旧用户名相同')
  }
  try {
    await api.put(`/api/users/updateUsername`, {
      oldUsername: user.value?.username,
      newUsername: newUsername.value,
    })
    alert('用户名修改成功')
    username.value = newUsername.value
    newUsername.value = ''
    fetchUserInfo()
  } catch (err: any) {
    const message = err.response?.data?.message || '用户名修改失败'
    alert(message)
  }
}
// 修改密码
async function updatePassword() {
  if (!oldPassword.value || !newPassword.value) {
    return alert('请输入旧密码和新密码')
  }
  try {
    const res = await api.put('/api/users/updatePassword', {
      username: user.value?.username,
      oldPassword: oldPassword.value,
      newPassword: newPassword.value,
    })
    alert(res.data.message || '密码修改成功')
    oldPassword.value = ''
    newPassword.value = ''
  } catch (err: any) {
    const message = err.response?.data?.message || '密码修改失败'
    alert(message)
  }
}

// 账户充值
async function handleRecharge() {
  if (!rechargeAmount.value || parseFloat(rechargeAmount.value) <= 0) {
    return alert('请输入有效的充值金额')
  }
  try {
    await api.post(`/api/users/${username.value}/recharge`, null, {
      params: { amount: parseFloat(rechargeAmount.value) },
    })
    alert('充值成功')
    rechargeAmount.value = ''
    fetchUserInfo() // 刷新用户信息
  } catch (err: any) {
    const message = err.response?.data?.message || '充值失败'
    alert(message)
  }
}
function goHome() {
  localStorage.setItem('username', username.value)
  router.push('/home')
}

onMounted(fetchUserInfo)
</script>

<style scoped>
.personal-center-container {
  position: relative;
  display: flex;
  gap: 40px;
  padding: 60px 80px;
  max-width: 1200px;
  margin: 0 auto;
  box-sizing: border-box;
}
.nav-header {
  position: absolute; /* 固定在页面某位置 */
  top: 20px;
  left: 30px;
  font-size: 25px;
  font-weight: bold;
  cursor: pointer;
  color: #007bff;
  z-index: 10;
  transition: opacity 0.3s;
}
.nav-header:hover {
  opacity: 0.8;
}

.personal-info-card,
.personal-edit-card {
  flex: 1;
  background-color: #ffffff;
  border-radius: 12px;
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.06);
  padding: 30px;
  transition: box-shadow 0.3s ease;
  min-height: 400px; /* 可根据需要调整高度 */
}

.personal-info-card:hover,
.personal-edit-card:hover {
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.1);
}

h2 {
  margin-bottom: 20px;
  font-size: 22px;
  color: #007bff;
  border-bottom: 2px solid #007bff;
  padding-bottom: 8px;
}

h3 {
  margin-top: 25px;
  font-size: 18px;
  color: #333;
}

.personal-info-card p {
  display: flex;
  /*justify-content: space-between;*/
  align-items: center;
  font-size: 16px;
  margin: 14px 0;
  border-bottom: 1px solid #eee;
  padding-bottom: 6px;
}

.personal-info-card p strong {
  margin-right: 6px; /* 控制字段名称和内容的紧凑间距 */
  color: #333;
  font-weight: 600;
  white-space: nowrap;
}

input {
  margin: 10px 0;
  padding: 10px 14px; /* 左右都设置为20px */
  width: 100%;
  box-sizing: border-box; /* 确保 padding 不会撑破宽度 */
  font-size: 14px;
  border: 1px solid #ccc;
  border-radius: 6px;
  transition: border-color 0.3s;
}
input:focus {
  border-color: #007bff;
  outline: none;
}
button {
  background-color: #3399ff;
  color: white;
  padding: 10px 18px;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  margin-top: 8px;
  transition: background-color 0.3s ease;
}
button:hover {
  background-color: #007bff;
}
</style>
